package com.rrqs.activity.adapter;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.litesuits.http.request.content.multi.MultipartBody;
import com.litesuits.http.request.content.multi.StringPart;
import com.rrqs.MessageEvents;
import com.rrqs.activity.MyMapLocation;
import com.rrqs.activity.OrderDetailNewActivity;
import com.rrqs.activity.common.Common;
import com.rrqs.activity.common.Const;
import com.rrqs.activity.data.DaoDianData;
import com.rrqs.activity.data.OrderWaitData;
import com.rrqs.net.AsyncHttpClient;
import com.rrqs.net.HttpResponseListener;
import com.rrqs.util.MyApplication;
import com.rrqs.utils.JsonUtils;
import com.rrqs.views.CountDownTimer;
import com.zadtek.xmqishi.R;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.List;

public class OrderWaitAdapter extends CommonAdapter<OrderWaitData> {
    private String formatAddress = "";
    private CountDownTimer timer;
    private SparseArray<CountDownTimer> timers;

    public OrderWaitAdapter(Context context, List<OrderWaitData> datas, int layoutId) {
        super(context, datas, layoutId);
        // TODO Auto-generated constructor stub
        timers = new SparseArray<>();
    }

    @Override
    public void convert(ViewHolders holder, final OrderWaitData t,final int position) {
        TextView newtaskmomey = holder.getView(R.id.waitgood_money);
        TextView newtasktime = holder.getView(R.id.waitgood_time);
        TextView order_number = holder.getView(R.id.order_number);
        TextView extra_reward = holder.getView(R.id.extra_reward);
        TextView newtask_goods_getaddress = holder.getView(R.id.wait_goods_getaddress);
        TextView getgpsaddr = holder.getView(R.id.getgpsaddr);
        TextView orderStartTime = holder.getView(R.id.orderStartTime);
        TextView orderEndTime = holder.getView(R.id.orderEndTime);
        TextView order_end_time_stamp = holder.getView(R.id.order_end_time_stamp);
        ProgressBar progress = holder.getView(R.id.progress);

        newtaskmomey.setText("¥" + "" + t.getReturnpay());
        order_number.setText("订单编号：" + "" + t.getMain_id());
        extra_reward.setText(" +" + "" + t.getExtra_reward());

        orderStartTime.setText(t.getOrder_start_time());
        orderEndTime.setText(t.getOrder_end_time());
        progress.setProgress((int) (t.getRate() * 100));

        int order_end_time_stamp1 = t.getOrder_end_time_stamp();
        //获取当前时间戳
        long timeStamp = System.currentTimeMillis() / 1000;

        CountDownTimer countDownTimer = timers.get(order_end_time_stamp.hashCode());
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }

        long s1 = order_end_time_stamp1 - timeStamp;
        long s2 = timeStamp - order_end_time_stamp1;
        if (s1 > 0) {
            countdown(s1, order_end_time_stamp, false, s2);
        } else {
            if (s1 + 36000 > 0) {
                countdown((s1 + 36000), order_end_time_stamp, true, s2);
            } else {
                order_end_time_stamp.setText("已超时");
            }
        }

        if (!t.getAdd_time().equals("") || t.getAdd_time() != null) {
            newtasktime.setText(Common.getStrTime(t.getAdd_time()));
        }

        try {
            String address_road = t.getAddress_road();
            if (address_road == null || address_road.equals("") || address_road.equals("null")) {
                String addrss = t.getGps_addrs();
                if (addrss != null && !addrss.equals("")) {
                    getgpsaddr.setText(addrss); // 根据经纬度反查地址
                    getgpsaddr.setVisibility(View.VISIBLE);
                } else {
                    getgpsaddr.setVisibility(View.GONE);
                }
            } else {
                getgpsaddr.setText(address_road); // 根据经纬度反查地址
                getgpsaddr.setVisibility(View.VISIBLE);
            }
        } catch (Exception e) {
        }

        newtask_goods_getaddress.setText(t.getSendaddress());
        LinearLayout submitthread = holder.getView(R.id.submitthread);
        ListView ItemList = holder.getView(R.id.waitgood_itemlist);
        OrderWaitItemAdapter itemadapter = new OrderWaitItemAdapter(mContext,
                t.getOrderItemList(), R.layout.waitgoodlist_itemlist_item,
                t.getMain_id());
        ItemList.setAdapter(itemadapter);

        submitthread.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (t.getMain_id() != null && !t.getMain_id().equals("")) {
                    Intent intent = new Intent(mContext, OrderDetailNewActivity.class);
                    intent.putExtra("mainid", t.getMain_id());
                    intent.putExtra("status", "wait");
                    mContext.startActivity(intent);
                }
            }
        });
        //底部按钮点击相关
        TextView lianxiguke = holder.getView(R.id.lianxiguke);
        TextView laixishangjia = holder.getView(R.id.laixishangjia);
        TextView ditudaohang = holder.getView(R.id.ditudaohang);
        TextView querenquhuo = holder.getView(R.id.querenquhuo);
        TextView shangbaodaodian = holder.getView(R.id.shangbaodaodian);
        lianxiguke.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                callPhoneNumber(t.getOrderItemList().get(0).getPhone());
            }
        });
        laixishangjia.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                callPhoneNumber(t.getOrderItemList().get(0).getSite_phone());
            }
        });
        ditudaohang.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Addressclick(t.getLat(),t.getLng());
            }
        });
        if(t.getFan_status().equals("6")){
            querenquhuo.setVisibility(View.GONE);
            shangbaodaodian.setVisibility(View.VISIBLE);
        }else{
            querenquhuo.setVisibility(View.VISIBLE);
            shangbaodaodian.setVisibility(View.GONE);
        }
        querenquhuo.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onButtonClick("2",t,position);
            }
        });
        shangbaodaodian.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onButtonClick("1",t,position);
            }
        });
    }
    // 电话
    public void callPhoneNumber(String phoneNumber) {
        if (phoneNumber != null && !phoneNumber.equals("")) {
            Intent intent = new Intent(Intent.ACTION_DIAL);
            intent.setData(Uri.parse("tel:" + phoneNumber));
            if (intent.resolveActivity(mContext.getPackageManager()) != null) {
                mContext.startActivity(intent);
            }
        }
    }
    private void Addressclick(String lat,String lng) {
        if (!lat.equals("0.0") && null != lat && !lng.equals("0.0") && null != lng && !lat.equals("null") && !lng.equals("null")) {
            Intent intent = new Intent(mContext, MyMapLocation.class);
            intent.putExtra("lat", lat);
            intent.putExtra("lng", lng);
            mContext.startActivity(intent);
        } else {
            Common.DisplayToast(mContext, "坐标获取失败！", 2);
        }
    }

    private void countdown(final long s, final TextView tv, final boolean isTimeOut, final long s2) {
        /** 倒计时s秒，一次1秒 */
        CountDownTimer timer = new CountDownTimer(s * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                // TODO Auto-generated method stub
                long ss;
                if (isTimeOut) {
                    ss = s2 + s - millisUntilFinished / 1000;
                } else {
                    ss = millisUntilFinished / 1000;
                }
                if (ss < 60) {
                    if (isTimeOut) {
                        tv.setText("超时" + ss + "秒");
                    } else {
                        tv.setText("剩余" + ss + "秒");
                    }
                } else if (millisUntilFinished < 3600) {
                    if (isTimeOut) {
                        tv.setText("超时" + ss / 60 + "分" + ss % 60 + "秒");
                    } else {
                        tv.setText("剩余" + ss / 60 + "分" + ss % 60 + "秒");
                    }
                } else {
                    if (isTimeOut) {
                        tv.setText("超时" + ss / 3600 + "时" + ss % 3600 / 60 + "分" + ss % 60 + "秒");
                    } else {
                        tv.setText("剩余" + ss / 3600 + "时" + ss % 3600 / 60 + "分" + ss % 60 + "秒");
                    }
                }
            }

            @Override
            public void onFinish() {
                if (isTimeOut) {
                    tv.setText("已超时");
                } else {
                    countdown(36000, tv, true, 0);
                }
            }
        }.start();

        timers.put(tv.hashCode(), timer);
    }
    private void onButtonClick(String status,final OrderWaitData t,final int position){
        AsyncHttpClient httpClient = new AsyncHttpClient(MyApplication.getInstace());
        SharedPreferences sp = com.rrqs.util.MyApplication.getInstace().getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
        String uid = sp.getString("uid", "");
        MultipartBody body = new MultipartBody();
        body.addPart(new StringPart("emp_id", uid));
        body.addPart(new StringPart("ince", "get_rr_help_wait_order_anniu"));
        body.addPart(new StringPart("main_id", ""+t.getMain_id()));
        body.addPart(new StringPart("lng", Const.lontitude));
        body.addPart(new StringPart("lat", Const.latitude));
//        body.addPart(new StringPart("lng", t.getLng()));//测试用
//        body.addPart(new StringPart("lat", t.getLat()));//测试用
        body.addPart(new StringPart("status", status));
        body.addPart(new StringPart("types", t.getTypes()+""));
        httpClient.post("http://xmpc.zadtek.com/mobile/Qs/index", body, new HttpResponseListener() {
            @Override
            public void onFailure(Throwable error) {
                super.onFailure(error);
            }
            @SuppressWarnings("unchecked")
            @Override
            public void onSuccess(String status, String result) {
                super.onSuccess(status, result);
                try {
                    Log.i("CYX","报告到店"+result);
                    JSONObject jsonObject = new JSONObject(result);
                    Log.i("CYX","报告到店"+jsonObject);
                }catch (Exception e){
                }
                DaoDianData resp = JsonUtils.json2Class(result,DaoDianData.class);
                if (resp.getStatus() == 1){
                    if(t.getFan_status().equals("6")) {
                        mDatas.get(position).setFan_status("16");
                        notifyDataSetChanged();
                    }else{
                        mDatas.remove(position);
                        notifyDataSetChanged();
                        EventBus.getDefault().post(new MessageEvents().setEventsType("mainshuaxin"));
                    }
                }
                Toast.makeText(mContext,resp.getSucess(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}
